package models

import (
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
)

// 支持的token表
type Token struct {
	Id       int
	Symbol   string
	ApiId    float64
	Protocol string
	Source   string
	EthAddrs []*EthAddr `orm:"reverse(many)"`
	Deny     bool
	Decimals float64
	IsMarket bool
	IsDelete bool
}

// 钱包地址表
type EthAddr struct {
	Id      int
	EthAddr string
	Tokens  []*Token `orm:"rel(m2m)"`
}

// 获取支持的token
func GetSupportedTokens() ([]*Token, error) {
	var res []*Token

	o := orm.NewOrm()
	num, err := o.QueryTable("Token").Exclude("is_delete", true).All(&res)

	if err != nil || num == 0 {
		logs.Debug("query tokens failed:", err)
		return nil, err
	}

	return res, err
}

// 获取用户token
func GetTokens(ethAddr string) ([]Token, error) {
	var tokens []Token
	o := orm.NewOrm()
	num, err := o.QueryTable("Token").Filter("EthAddrs__EthAddr__EthAddr", ethAddr).All(&tokens)

	// 加载关系字段
	for _, token := range tokens {
		o.LoadRelated(&token, "EthAddrs")
	}

	if err != nil || num == 0 {
		logs.Debug("query tokens failed:", err)
		return nil, err
	}

	return tokens, err
}
